package com.breeze.webview.commands;

import android.os.RemoteException;
import android.util.Log;

import com.breeze.base.autoservice.BreezeServiceLoader;
import com.breeze.common.eventbus.LoginEvent;
import com.breeze.common.usercenter.IUserCenterService;
import com.breeze.webview.IWebViewProcessCallbackInterface;
import com.breeze.webview.command.WebViewCommand;
import com.google.auto.service.AutoService;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

@AutoService(WebViewCommand.class)
public class LoginCommand implements WebViewCommand {
    private static final String TAG = "LoginCommand";
    private IUserCenterService userCenterService;
    private IWebViewProcessCallbackInterface callback;
    private String callbackName;

    public LoginCommand() {
        EventBus.getDefault().register(this);
        userCenterService = BreezeServiceLoader.load(IUserCenterService.class);
    }

    @Override
    public String name() {
        return "login";
    }

    @Override
    public void execute(Map<String, String> params, IWebViewProcessCallbackInterface callback) {
        // 未登录再进行登录
        if (userCenterService != null && !userCenterService.isLogined()) {
            callbackName = params.get("callbackName");
            this.callback = callback;
            userCenterService.login();
        }
    }

    @Subscribe
    public void onMessageEvent(LoginEvent loginEvent) {
        Log.i(TAG, "onMessageEvent: ");
        HashMap map = new HashMap();
        map.put("accountName", loginEvent.userName);
        if (callback != null) {
            try {
                // IPC跨进程调用到WebView所在进程
                callback.onResult(callbackName, new Gson().toJson(map)/*转化为json数据*/);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
}
